import { http } from '@/utils';

// 获取频道数据 action
export const getChannels = () => {
  return async (dispatch) => {
    // 发起异步请求获取数据
    const res = await http.get('/channels');
    // 请求成功分发action
    // console.log('channels===>', res.data.data);

    dispatch({
      type: 'article/getChannels',
      payload: res.data.data.channels,
    });
  };
};
// 获取文章列表
export const getArticles = (params) => {
  return async (dispatch) => {
    let formatParams = {};
    // 处理状态
    if (params.status !== -1) {
      formatParams.status = params.status;
    }
    // 处理频道
    if (params.channelId !== -1) {
      formatParams.channel_id = params.channelId;
    }
    // 日期范围
    if (params.dateStart) {
      formatParams.begin_pubdate = params.dateStart;
    }
    if (params.dateEnd) {
      formatParams.end_pubdate = params.dateEnd;
    }
    // 分页
    formatParams.page = params.page;
    formatParams.per_page = params.pageSize;

    const res = await http.get('/mp/articles', { params: formatParams });

    const { results: list, total_count: total } = res.data.data;

    dispatch({
      type: 'article/getArticles',
      payload: {
        // 将数据格式化成 Table 需要的格式
        list: list.map((item) => {
          return {
            ...item,
            cover: item.cover.images[0],
          };
        }),
        total,
      },
    });
  };
};
// 删除文章
export const deleteArticle = (id, params) => {
  return async (dispatch) => {
    console.log(id, params);
    await http.delete(`/mp/articles/${id}`);
    // 继续分发异步 action，获取最新的文章列表数据
    dispatch(getArticles(params));
  };
};
// 发表文章
export const publishArticle = (data) => {
  return (dispatch) => {
    // 处理接口数据
    console.log('发表文章 action 中接收到的数据', data);
    const isDraft = data.publishType === 'draft' ? true : false;
    const postData = {
      title: data.values.title,
      content: data.values.content,
      channel_id: data.values.channelId,
      cover: {
        type: data.values.type,
        images: data.fileList.map((item) => item.response.data.url),
      },
    };
    console.log('格式化后的数据', postData);
    // 调用接口
    if (data.articleId) {
      // 编辑
      http.put(`/mp/articles/${data.articleId}?draft=${isDraft}`, postData);
    } else {
      // 发布
      http.post(`/mp/articles?draft=${isDraft}`, postData);
    }
  };
};
// 获取文章详情
export const getArticleById = (articleId) => {
  return async (dispatch) => {
    const res = await http.get(`/mp/articles/${articleId}`);
    console.log('res', res);
    const {
      id,
      title,
      channel_id: channelId,
      content,
      cover: { type, images },
    } = res.data.data;

    const article = {
      id,
      title,
      channelId,
      content,
      type,
      images,
    };

    dispatch({
      type: 'article/getArticleById',
      payload: article,
    });
  };
};
